package org.keyyond.ms.business.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.keyyond.ms.business.model.MsbusinessEsbFormatConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class CreateDataUtil {
	
	private static Logger logger = LoggerFactory.getLogger(CreateDataUtil.class);
	
	private static final String ROOTFATHERID = "0";//根标签父级id
	
	private static final String ISEND = "1";//末级
	
	private static final String FORMAT1 = "${item}";//替换标志(不带双影号)
	
	private static final String FORMAT2 = "#{item}";//替换标志(带双影号)
	
	public static final String JSON = "json";//json格式
	
	public static final String XML = "xml"; //xml格式
	
	public static final String MAP = "map"; //key：value格式
	
	public static String createXml(List<MsbusinessEsbFormatConfig> configList,Map param){
		
		StringBuffer sendContent = new StringBuffer();
		MsbusinessEsbFormatConfig root = null;
		try{
			//获取根节点root
			List<MsbusinessEsbFormatConfig> rootList = getConfigByFatherId(configList,ROOTFATHERID);
			if(rootList.size()>0){
				root=rootList.get(0);
			}
			if(root==null){
				throw new Exception("根节点缺失");
			}
			handleNode(sendContent,param,root,configList);
		}catch(Exception e){
			logger.error(e.getMessage());
			e.printStackTrace();
			sendContent.setLength(0);
		}
		return sendContent.toString();
	}
	
	public static String createJson(List<MsbusinessEsbFormatConfig> configList,Map param){
		StringBuffer sendContent = new StringBuffer();
		MsbusinessEsbFormatConfig root = null;
		try{
			//获取根节点root
			List<MsbusinessEsbFormatConfig> rootList = getConfigByFatherId(configList,ROOTFATHERID);
			if(rootList.size()>0){
				root=rootList.get(0);
			}
			if(root==null){
				throw new Exception("根节点缺失");
			}
			handleNode2(sendContent,param,root,configList);
		}catch(Exception e){
			logger.error(e.getMessage());
			e.printStackTrace();
			sendContent.setLength(0);
		}
		return sendContent.toString();
	}
	
	public static String createMap(List<MsbusinessEsbFormatConfig> configList,Map param){
		StringBuffer sendContent = new StringBuffer();
		for(int i=0;i<configList.size();i++){
			MsbusinessEsbFormatConfig config = configList.get(i);
			Object value = getValueByKey(param,config.getKey());
			String contentform = config.getContentform();
			sendContent.append(config.getLabel()).append("=");
			if(!StringUtils.isEmpty(contentform)){
				sendContent.append(replaceString(contentform,value));
			}else{
				sendContent.append(value);
			}
			if(i!=configList.size()-1){
				sendContent.append("&");
			}
		}
		return sendContent.toString();
	}
	
	public static StringBuffer handleNode2(StringBuffer sendContent,Object param,MsbusinessEsbFormatConfig config,List<MsbusinessEsbFormatConfig> configList) throws ClassNotFoundException{
		sendContent.append(config.getLabel());
		if(param!=null){
			Object node = null;
			//获取子节点
			Class<?> clazz = Class.forName(config.getContenttype());
			
			List<MsbusinessEsbFormatConfig> sonNodes = getConfigByFatherId(configList,config.getSeqno());
			if(sonNodes.size()>0){
				if(OftenUseClasses.LIST.isAssignableFrom(clazz)){
					sendContent.append("[");
					for(Object obj:(List)param){
						for(MsbusinessEsbFormatConfig sonConfig:sonNodes){
							handleNode2(sendContent,obj,sonConfig,configList);
						}
						if(((List)param).indexOf(obj)!=((List)param).size()-1){
							sendContent.append(",");
						}
					}
					sendContent.append("]");
				}else if(OftenUseClasses.MAP.isAssignableFrom(clazz)){
					for(MsbusinessEsbFormatConfig sonConfig:sonNodes){
						node =getValueByKey(param,sonConfig.getKey());
						handleNode2(sendContent,node,sonConfig,configList);
						if(sonNodes.indexOf(sonConfig)!=sonNodes.size()-1){
							sendContent.append(",");
						}
					}
				}
			}else{
				sendContent.append(":");
				Object value = getValueByKey(param,config.getKey());
				String contentform = config.getContentform();
				if(!StringUtils.isEmpty(contentform)){
					sendContent.append(replaceString(contentform,value));
				}else{
					sendContent.append(value);
				}
			}
		}
		sendContent.append(config.getLastlabel());
		return sendContent;
	}
	
	
	
	public static List<MsbusinessEsbFormatConfig> getConfigByFatherId(List<MsbusinessEsbFormatConfig> configList,String fatherId){
		List<MsbusinessEsbFormatConfig> sonConfigs = new ArrayList<MsbusinessEsbFormatConfig>();
		if(configList!=null&&configList.size()>=0){
			for(MsbusinessEsbFormatConfig config:configList){
				if(config.getFatherid().equals(fatherId)){
					sonConfigs.add(config);
				}
			}
		}
		return sonConfigs;
	}
	
	
	public static StringBuffer handleNode(StringBuffer sendContent,Object param,MsbusinessEsbFormatConfig config,List<MsbusinessEsbFormatConfig> configList) throws ClassNotFoundException{
		sendContent.append(config.getLabel());
		if(param!=null){
			Object node = null;
			//获取子节点
			Class<?> clazz = Class.forName(config.getContenttype());
			
			List<MsbusinessEsbFormatConfig> sonNodes = getConfigByFatherId(configList,config.getSeqno());
			if(sonNodes.size()>0){
				if(OftenUseClasses.LIST.isAssignableFrom(clazz)){
					for(Object obj:(List)param){
						for(MsbusinessEsbFormatConfig sonConfig:sonNodes){
							handleNode(sendContent,obj,sonConfig,configList);
						}
					}
				}else if(OftenUseClasses.MAP.isAssignableFrom(clazz)){
					for(MsbusinessEsbFormatConfig sonConfig:sonNodes){
						node =getValueByKey(param,sonConfig.getKey());
						handleNode(sendContent,node,sonConfig,configList);
					}
				}
			}else{
				Object value = getValueByKey(param,config.getKey());
				String contentform = config.getContentform();
				if(!StringUtils.isEmpty(contentform)){
					sendContent.append(replaceString(contentform,value));
				}else{
					sendContent.append(value);
				}
			}
		}
		sendContent.append(config.getLastlabel());
		return sendContent;
	}
	
	   /**
     * 单个对象的某个键的值
     * 
     * @param object
     *            对象
     * 
     * @param key
     *            键
     * 
     * @return Object 键在对象中所对应得值 没有查到时返回空字符串
     */
    public static Object getValueByKey(Object obj, String key) {
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        if(OftenUseClasses.MAP.isAssignableFrom(userCla)){
        	Object value=((Map)obj).get(key);
        	return value;
        }else if(OftenUseClasses.STRING.isAssignableFrom(userCla)){
        	return (String)obj;
        }else if(OftenUseClasses.LIST.isAssignableFrom(userCla)){
        	return ((List)obj).get(Integer.parseInt(key));
        }else if(OftenUseClasses.INTEGER.isAssignableFrom(userCla)){
        	return (Integer)obj;
        }else if(OftenUseClasses.BYTE.isAssignableFrom(userCla)){
        	return (Byte)obj;
        }else if(OftenUseClasses.SHORT.isAssignableFrom(userCla)){
        	return (Short)obj;
        }else if(OftenUseClasses.LONG.isAssignableFrom(userCla)){
        	return (Long)obj;
        }else if(OftenUseClasses.FLOAT.isAssignableFrom(userCla)){
        	return (Float)obj;
        }else if(OftenUseClasses.DOUBLE.isAssignableFrom(userCla)){
        	return (Double)obj;
        }else if(OftenUseClasses.BOOLEAN.isAssignableFrom(userCla)){
        	return (Boolean)obj;
        }else{
        	 Field[] fs = userCla.getDeclaredFields();
             for (int i = 0; i < fs.length; i++) {
                 Field f = fs[i];
                 f.setAccessible(true); // 设置些属性是可以访问的
                 try {
                 
                     if (f.getName().endsWith(key)) {
                         System.out.println("单个对象的某个键的值==反射==" + f.get(obj));
                         return f.get(obj);
                     }
                 } catch (IllegalArgumentException e) {
                     e.printStackTrace();
                 } catch (IllegalAccessException e) {
                     e.printStackTrace();
                 }
             }
        }
        // 没有查到时返回空字符串
        return "";
    }
    
    public static String replaceString(String format,Object obj){
    	StringBuffer sb  = new StringBuffer(format);
    	if(format.contains(FORMAT1)){
    		while(sb.indexOf(FORMAT1)!=-1){
    			int i = sb.indexOf(FORMAT1);
    			sb.replace(i, i+FORMAT1.length(),String.valueOf(obj));
    		}
    	}
    	if(format.contains(FORMAT2)){
    		while(sb.indexOf(FORMAT2)!=-1){
    			int i = sb.indexOf(FORMAT2);
    			sb.replace(i, i+FORMAT2.length(),"\""+String.valueOf(obj)+"\"");
    		}
    	}
    	return sb.toString();
    }
    
    public static void main(String[] args) {
//    	String replaceString = replaceString("${item}元${item}",1);
//    	System.out.println(replaceString);
    	MsbusinessEsbFormatConfig config = new MsbusinessEsbFormatConfig();
    	config.setContenttype("java.lang.String");
    	config.setKey("username");
    	config.setLabel("username");
    	MsbusinessEsbFormatConfig config2 = new MsbusinessEsbFormatConfig();
    	config2.setContenttype("java.lang.String");
    	config2.setKey("password");
    	config2.setLabel("password");
    	List<MsbusinessEsbFormatConfig> list = new ArrayList<MsbusinessEsbFormatConfig>();
    	list.add(config);
    	list.add(config2);
    	Map map = new HashMap();
    	map.put("username", "tom");
    	map.put("password", "password");
    	String string = createMap(list,map);
    	System.out.println(string);
	}

}
